package com.reflection1;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @description:
 * @author: jhy
 * @time: 2021/4/23 20:35
 */
public class ReflectApiTest {

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, NoSuchFieldException {

        //通过Class.forName("")得到Class对象
        Class cls = Class.forName("com.reflection1.Dog");

        //1通过Class对象的newInstance方法得到实例对象
        Object o = cls.newInstance();
        System.out.println(o);//com.reflection1.Dog@1b6d3586

        //2.通过Class对象的getMethod方法得到Method对象-->方法对象
        Method sayMethod = cls.getMethod("say");
        System.out.println(sayMethod);//public void com.reflection1.Dog.say()

        //3.通过Class对象的getConstruct()得到无参构造器
        Constructor constructor = cls.getConstructor();
        System.out.println(constructor);//public com.reflection1.Dog()

        //4.通过Class对象的getConstruct(传入参数类型的Class对象)得到相应的有参构造器
        Constructor constructor1 = cls.getConstructor(String.class);
        System.out.println(constructor1);//public com.reflection1.Dog(java.lang.String)

        //5.通过Class对象的getField(传入字段名称)得到相应的字段
        Field ageField = cls.getField("age");
        System.out.println(ageField);//public int com.reflection1.Dog.age

    }
}
